<template>
  <el-dialog
    v-loading="isLoading"
    class="dialog"
    :title="isEdit ? '跟着练详情' : '上传跟着练'"
    :visible.sync="dialogVisible"
    width="800px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="save"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="90px">
      <div class="common">
        <el-form-item prop="pfJobName" label="作业名称:">
          <el-input
            :disabled="!show"
            style="width: 70%"
            clearable
            placeholder="请输入作业名称"
            v-model="form.pfJobName"
          ></el-input>
        </el-form-item>

        <el-form-item label="适合人群:" prop="pfPscId">
          <div style="display: flex; width: 80%">
            <el-select
              :disabled="!show"
              v-model="form.pfPscId"
              placeholder="年级"
              style="margin-right: 10px"
            >
              <el-option
                v-for="item in gradelist"
                :key="item.gradeId"
                :label="item.gradeName"
                :value="item.gradeId"
              >
              </el-option>
            </el-select>
            <el-select
              :disabled="!show"
              v-model="form.pfSex"
              placeholder="性别"
            >
              <el-option
                v-for="item in options1"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
        </el-form-item>
      </div>
      <div class="common">
        <el-form-item label="简介:" prop="pfIntroduction">
          <el-input
            :disabled="!show"
            type="textarea"
            style="width: 560px"
            v-model="form.pfIntroduction"
          ></el-input>
        </el-form-item>
      </div>

      <el-form-item label="封面图" prop="pfImgUrl">
        <el-upload
          :disabled="!show"
          style="width: 800px"
          class="upload-demo"
          drag
          v-loading="loading"
          :on-success="picUpload"
          :before-upload="beforeUpload"
          :action='$env.BASE_URL+"/homework/zhty/public/import_file"'
          name="file"
          :headers="{
            'access-token': $store.state.user.TOKEN,
          }"
          multiple
        >
          <div v-if="!form.pfImgUrl">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
          </div>
          <img
            style="width: auto; height: auto; max-height: 100%; max-width: 100%"
            v-if="form.pfImgUrl"
            :src="$store.state.user.BASE_URL + form.pfImgUrl"
            alt=""
          />
          <div class="el-upload__tip" slot="tip">
            只能上传jpg/png文件，且不超过500kb.  <span style="color: #ec3c3c">建议图片尺寸为16:9</span>
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item label="视频:" prop="pfVideoUrl">
        <el-upload
          :disabled="!show"
          style="width: 800px"
          class="upload-demo"
          drag
          :on-progress="uploadVideoProcess"
          :on-success="videoUpload"
          :before-upload="beforeUpload1"
          v-bind:show-file-list="false"
          :action='$env.BASE_URL+"/homework/zhty/public/import_file"'
          :headers="{
            'access-token': $store.state.user.TOKEN,
          }"
        >
          <div v-if="form.pfVideoUrl == '' && !videoFlag">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
          </div>
          <video
            style="width: auto; height: auto; max-height: 100%; max-width: 100%"
            v-if="form.pfVideoUrl != '' && !videoFlag"
            :src="$store.state.user.BASE_URL + form.pfVideoUrl"
            controls="controls"
          />
          <div class="el-upload__tip" slot="tip">
            <span style="color: #ec3c3c">建议上传竖屏视频，方便学生练习</span>
          </div>
          <el-progress
            v-if="videoFlag == true"
            type="circle"
            v-bind:percentage="videoUploadPercent"
            style="margin-top: 32px"
          ></el-progress>
        </el-upload>
      </el-form-item>

      <div class="common">
        <el-form-item label="循环:" prop="checkedBoxWeek">
          <el-checkbox-group
            @change="handleCheckedCitiesChange"
            :disabled="!show"
            v-model="form.checkedBoxWeek"
            size="small"
          >
            <el-checkbox
              border
              style="margin-right: 1px"
              v-for="item in week"
              :label="item.value"
              :key="item.value"
              >{{ item.label }}</el-checkbox
            >
          </el-checkbox-group>
          <el-checkbox
          :disabled="!show"
          border
          size="small"
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
        </el-form-item>
      </div>
      <div class="common">
        <el-form-item
          v-if="!!form.pfCheckInfo"
          label="审核原因:"
          prop="pfCheckInfo"
        >
          <span style="color: red">{{ form.pfCheckInfo }}</span>
        </el-form-item>
      </div>
    </el-form>
    <span slot="footer" class="dialog-footer" v-if="show">
      <el-button size="small" @click="save()">取 消</el-button>
      <el-button
        size="small"
        :loading="buttonLoading"
        type="primary"
        @click="submit()"
        >确 定</el-button
      >
    </span>
    <span slot="footer" class="dialog-footer" v-if="!show">
    </span>
  </el-dialog>
</template>

<script>
import {
  homeworkList,
  homeworkDetails,
  saveHomework,
} from "@/api/followThePractice/index.js";
const weeks = [
  {
    label: "周一",
    value: "1",
  },
  {
    label: "周二",
    value: "2",
  },
  {
    label: "周三",
    value: "3",
  },
  {
    label: "周四",
    value: "4",
  },
  {
    label: "周五",
    value: "5",
  },
  {
    label: "周六",
    value: "6",
  },
  {
    label: "周日",
    value: "7",
  },
];
export default {
  data() {
    return {
      isIndeterminate: false,
      checkAll: false,
      isShowUploadVideo: false,
      videoFlag: false,
      videoUploadPercent: "",
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      options: [],
      options1: [
        {
          value: "1",
          label: "男",
        },
        {
          value: "2",
          label: "女",
        },
        {
          value: "3",
          label: "全性别",
        },
      ],

      week: weeks,
      isLoading: false,
      loading: false,
      buttonLoading: false,
      form: {
        pfJobName: "",
        pfImgUrl: "",
        pfVideoUrl: "",
        pfPscId: "",
        pfSex: "",
        pfIntroduction: "",
        checkedBoxWeek: [],
      },
      rules: {
        pfJobName: [
          {
            required: true,
            message: "请输入学生姓名",
          },
        ],
        pfIntroduction: [
          {
            required: true,
            message: "请输入简介",
          },
        ],
        pfPscId: [
          {
            validator: this.validatePhone,
            trigger: "change",
            region: [
              { required: true, message: "请选择活动区域", trigger: "" },
            ],
          },
        ],
        pfImgUrl: [
          {
            required: true,
            message: "请上传图片",
          },
        ],
        pfVideoUrl: [
          {
            required: true,
            message: "请上传视频",
          },
        ],
        checkedBoxWeek: [
          {
            required: true,
            message: "请选择日期",
          },
        ],
      },
    };
  },
  computed: {
    show() {
      if (this.item.pfCheckStatus == 1) {
        return false;
      } else {
        return true;
      }
    },
  },
  watch: {
    isEdit: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          this.getStudentMessage(this.item.pfId);
        }
      },
    },
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
    item: {
      type: Object,
      default: {},
    },
    gradelist: {
      type: Array,
      default: [],
    },
    dialogVisible: {
      type: Boolean,
    },
  },

  methods: {
    handleCheckAllChange(val) {
      this.form.checkedBoxWeek = val ? weeks.map((item) => item.value) : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.week.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.week.length;
    },

    validatePhone(rule, value, callback) {
      if (!this.form.pfSex && !this.form.pfPscId) {
        callback(new Error("请选择"));
      }
      if (!this.form.pfPscId) {
        callback(new Error("请选择年级"));
      }
      if (!this.form.pfSex) {
        callback(new Error("请选择性别"));
      } else {
        callback(); // 通过
      }
    },
    beforeUpload(file) {
      this.loading = true;
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const types = ["jpeg", "jpg", "png"];
      if (!types.includes(fileSuffix)) {
        this.$message.error(`文件只能是 ${types.join()} 格式!`);
        this.loading = false;
      }
      return types.includes(fileSuffix);
    },
    uploadVideoProcess(event, file, fileList) {
      //注意在data中添加对应的变量名
      this.videoFlag = true;
      this.videoUploadPercent = file.percentage.toFixed(0) * 1;
    },
    videoUpload(e) {
      this.isShowUploadVideo = true;
      this.videoFlag = false;
      this.videoUploadPercent = 0;
      if (e.code === 200) {
        this.form.pfVideoUrl = e.result.pic;
      } else if (e.code === 401) {
        this.$router.replace("/");
        this.$message.error("您的身份信息已过期，请重新登录");
        sessionStorage.removeItem("userInfo");
        sessionStorage.removeItem("token");
        this.$store.commit("user/SET_TOKEN", "");
      } else {
        this.$message.error(e.message);
      }
    },
    beforeUpload1(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const types = [
        "avi",
        "mov",
        "mpg",
        "mpeg",
        "rmvb",
        "mp4",
        "flv",
        "rm",
        "mkv",
      ];
      if (!types.includes(fileSuffix)) {
        this.$message.error(`文件只能是 ${types.join()} 格式!`);
      }
      this.isShowUploadVideo = false;
      return types.includes(fileSuffix);
    },
    validator() {
      this.$refs.form.validate(() => {});
    },
    save(done) {
      this.$emit("close", done);
    },
    picUpload(e) {
      if (e.code === 200) {
        this.form.pfImgUrl = e.result.pic;
      } else if (e.code === 401) {
        this.$router.replace("/");
        this.$message.error("您的身份信息已过期，请重新登录");
        sessionStorage.removeItem("userInfo");
        sessionStorage.removeItem("token");
        this.$store.commit("user/SET_TOKEN", "");
      } else {
        this.$message.error(e.message);
      }
      this.loading = false;
    },
    getStudentMessage(id) {
      this.isLoading = true;
      let data = { pfId: id };
      homeworkDetails(data).then((response) => {
        if (response.code === 200) {
          this.form = response.result;
          this.form.pfPscId = response.result.pfScId;
          // this.form.checkedBoxWeek=response.result.pfCurrentCycle.split(',').concat([]);
          this.$set(
            this.form,
            "checkedBoxWeek",
            response.result.pfCurrentCycle.split(",").concat([])
          );
        }
        this.isLoading = false;
      });
    },
    submit(done) {
      this.$refs.form.validate((e) => {
        if (e) {
          this.buttonLoading = true;
          let data = {
            pfJobName: this.form.pfJobName,
            pfScId: this.form.pfPscId,
            pfSex: this.form.pfSex,
            pfImgUrl: this.form.pfImgUrl,
            pfIntroduction: this.form.pfIntroduction,
            pfVideoUrl: this.form.pfVideoUrl,
            pfCurrentCycle: this.form.checkedBoxWeek.toString(),
            pfId: this.item.pfId ? this.item.pfId : null,
            pfShId: this.$store.state.user.USER_INFO.pscShId,
            pfUpdateId: this.$store.state.user.USER_INFO.id,
          };
          saveHomework(data).then((response) => {
            this.buttonLoading = false;
            if (response.code === 200) {
              this.$emit("submit", done);
              this.$message.success("添加成功！");
            } else {
              this.$message.error(response.message);
            }
          });
        }
      });
    },
    addPhone() {
      this.form.phoneNum.push({ id: this.form.phoneNum.length, mobile: "" });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .upload-demo {
  width: 100%;
}
::v-deep .el-dialog__body {
  height: 70vh;
  overflow-y: auto;
  overflow-x: hidden;
  &::-webkit-scrollbar {
    width: 10px;
    border-radius: 16px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 16px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 16px;
  }
}
.common {
  display: flex;
  justify-content: space-around;
  width: 100%;
  .el-form-item {
    flex: 1;
  }
}
::v-deep .el-dialog {
  margin-top: 8vh !important;
}
.el-icon-circle-plus-outline {
  margin-left: 20px;
  &::before {
    font-size: 24px;
    color: #409eff;
  }
}
.el-icon-delete {
  margin-left: 20px;
  &::before {
    font-size: 24px;
    color: #f56c6c;
  }
}
::v-deep .el-checkbox-button__inner {
  border-left: 1px solid #dcdfe6;
}
::v-deep .el-loading-mask {
  width: 600px;
  height: 180px;
}
::v-deep .el-upload-list__item {
  display: none;
}
::v-deep .el-upload--text {
  width: 100%;
}
::v-deep .el-upload-dragger {
  width: 70%;
}
::v-deep .el-form {
  padding-left: 60px;
}
</style>
